/*
 * MIT License
 *
 * Copyright (c) 2020 wen.gu <454727014@qq.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

/***************************************************************************
 * Name: thread_pool.cpp
 *
 * Purpose: thread pool implementation
 *
 * Developer:
 *   wen.gu , 2019-07-04
 *
 * TODO:
 *
 ***************************************************************************/

/******************************************************************************
 **    INCLUDES
 ******************************************************************************/

#include "panda/core/thread_pool.h"

#define LOG_TAG "ThdPool"
#include "panda/core/log.h"

namespace panda
{
namespace core
{
/******************************************************************************
 **    MACROS
 ******************************************************************************/


/******************************************************************************
 **    TYPE DEFINITIONS
 ******************************************************************************/

/******************************************************************************
 **    CLASSES/FUNCTIONS DEFINITIONS
 ******************************************************************************/

class ThreadPool::impl
{
public:
    uint32_t mMaxThreadCnt;
    std::vector<std::thread> mPool; /** thread pool */
    std::queue<Task> mTasks; /** task queue */
    std::mutex mLock; /** for thread pool */
    std::mutex mAPILock; /** for API mutex */
    std::condition_variable mCond;
    std::atomic<bool> mStoped;
    std::atomic<int>  mIdlThdNum;
};
 
 ///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////


ThreadPool::ThreadPool(uint32_t maxThreadCnt /*= MAX_THREAD_NUM*/)
    :mImpl(new impl)
{
    /** todo something */

    mImpl->mMaxThreadCnt = maxThreadCnt;
    mImpl->mStoped = true;
}

ThreadPool::~ThreadPool()
{
    /** todo something */
    stop();
}

///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////


PandaErrc ThreadPool::start(uint32_t threadCnt /**  = 4*/ )
{
    AutoLock al(mImpl->mAPILock);
    if (threadCnt <= mImpl->mMaxThreadCnt)
    {
        if (mImpl->mStoped)
        {
            mImpl->mStoped.store(false);
            mImpl->mIdlThdNum = threadCnt < 1 ? 1 : threadCnt;
            for (threadCnt = 0; threadCnt < (uint32_t)mImpl->mIdlThdNum; ++threadCnt)
            {   //initialize all thread in thread pool.
                mImpl->mPool.emplace_back([this]
                { // work thread function
                    //LOGD("===>: a thread pool's woker start running... \n");
                    while(!mImpl->mStoped)
                    {
                        std::function<void()> task;
                        {   // get a task to run.
                            AutoLock al(mImpl->mLock);

                            mImpl->mCond.wait(al, [this] {
                                    return this->mImpl->mStoped.load() || !this->mImpl->mTasks.empty();
                                }
                            ); // wait until have a task in queue.

                            if (mImpl->mStoped && mImpl->mTasks.empty())
                            {
                                break;
                            }
                                
                            task = std::move(mImpl->mTasks.front()); // get a task
                            mImpl->mTasks.pop();
                        }
                        mImpl->mIdlThdNum--;
                        task();
                        mImpl->mIdlThdNum++;
                    }
                    //LOGD("===>: a thread pool's worker exit...\n");
                }
                );
            }
            
            return PandaErrc::OK;
        }
        else
        {
            return PandaErrc::InvalidStatus;
        }      
    }

    return PandaErrc::BadParameter;
}

PandaErrc ThreadPool::stop()
{
    AutoLock al(mImpl->mAPILock);
    if (mImpl->mStoped == false)
    {
        mImpl->mStoped.store(true);
        mImpl->mCond.notify_all(); // wake up all thread in pool.
        for (std::thread& thread : mImpl->mPool)
        {
            //thread.detach(); // detach thread ”
            if (thread.joinable())
            {
                thread.join(); // wait task run to end， pre condition：The thread will definitely finish
            }                
        }

        return PandaErrc::OK;
    }

    return PandaErrc::InvalidStatus;
}


PandaErrc ThreadPool::commitTask(Task task)
{
    AutoLock al(mImpl->mAPILock);

    if (mImpl->mStoped == false)
    {
        {    // add task to queue
            std::lock_guard<std::mutex> lock{ mImpl->mLock };
            mImpl->mTasks.emplace(task);
        }

        mImpl->mCond.notify_one(); // wake up a thread to run.

        return PandaErrc::OK;
    }

    return PandaErrc::InvalidStatus;
}

uint32_t ThreadPool::idlThreadCount() const
{
    return mImpl->mIdlThdNum;
}

uint32_t ThreadPool::threadCount() const
{
    return (uint32_t)mImpl->mPool.size();
}

} /** namespace core */
} /** namespace panda */